package com.rbac.interfaces.controller;

import com.rbac.application.service.AuthService;
import com.rbac.common.result.Result;
import com.rbac.domain.dto.request.LoginRequest;
import com.rbac.domain.dto.request.RegisterRequest;
import com.rbac.domain.dto.response.LoginResponse;
import com.rbac.domain.dto.response.UserInfoResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

@Tag(name = "认证管理", description = "用户认证相关接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Validated @RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        String clientIp = getClientIp(httpRequest);
        return Result.success("登录成功", authService.login(request, clientIp));
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@Validated @RequestBody RegisterRequest request, HttpServletRequest httpRequest) {
        String clientIp = getClientIp(httpRequest);
        authService.register(request, clientIp);
        return Result.success();
    }

    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        authService.logout(token);
        return Result.success("登出成功");
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("/user-info")
    public Result<UserInfoResponse> getCurrentUser() {
        return Result.success(authService.getCurrentUser());
    }

    @Operation(summary = "刷新token")
    @PostMapping("/refresh")
    public Result<Void> refreshToken() {
        authService.refreshToken();
        return Result.success("Token刷新成功");
    }

    private String getClientIp(HttpServletRequest request) {
        String xIp = request.getHeader("X-Real-IP");
        String xFor = request.getHeader("X-Forwarded-For");
        if (xFor != null && !xFor.isEmpty() && !"unknown".equalsIgnoreCase(xFor)) {
            int index = xFor.indexOf(",");
            if (index != -1) {
                return xFor.substring(0, index);
            } else {
                return xFor;
            }
        }
        if (xIp != null && !xIp.isEmpty() && !"unknown".equalsIgnoreCase(xIp)) {
            return xIp;
        }
        return request.getRemoteAddr();
    }
}